//
//  UIButton+xib.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/9.
//

import Foundation
import UIKit
#if canImport(TCC_String)
import TCC_String
#endif
#if canImport(TCC_Extension)
import TCC_Extension
#endif
private var textHightLightKey = "cornarRadiusKey"
private var textSelectedKey = "backGroundHexColorKey"
private var textDisabledKey = "borderHexColorKey"
private var bgDisabledKey = "bgDisabledKey"

@objc public extension UIButton
{
    @IBInspectable var textHightLightColor:String{
        set{
            objc_setAssociatedObject(self, &textHightLightKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if newValue == "" {return}
            self.setTitleColor(color(newValue), for: .highlighted)
        }get{
            return objc_getAssociatedObject(self, &textHightLightKey) as? String ?? "#FFFFFF"
        }
    }
    
    @IBInspectable var textSelectedColor:String{
        set{
            objc_setAssociatedObject(self, &textSelectedKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if newValue == "" {return}
            self.setTitleColor(color(newValue), for: .selected)
        }get{
            return objc_getAssociatedObject(self, &textSelectedKey) as? String ?? "#FFFFFF"
        }
    }
    @IBInspectable var textDisabledColor:String{
        set{
            objc_setAssociatedObject(self, &textDisabledKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if newValue == "" {return}
            self.setTitleColor(color(newValue), for: .disabled)
        }get{
            return objc_getAssociatedObject(self, &textDisabledKey) as? String ?? "#FFFFFF"
        }
    }
    
    private func color(_ hex : String) -> UIColor
    {
        var cString = hex.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        if (cString.count < 6)
        {
            return .white
        }
        if cString.hasPrefix("0X")
        {
            cString = cString[2...cString.count]
        }
        if cString.hasPrefix("#")
        {
            cString = cString[1...cString.count]
        }
        if cString.count != 6
        {
            return .white
        }
        
        //R.G.B
        let rString = cString[0...1]
        let gString = cString[2...3]
        let bString = cString[4...5]
        
        //存储转换后的数值
        var r : UInt64 = 0, g : UInt64  = 0, b : UInt64 = 0
        Scanner(string: rString).scanHexInt64(&r)
        Scanner(string: gString).scanHexInt64(&g)
        Scanner(string: bString).scanHexInt64(&b)
        return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255.0, alpha:CGFloat(alpha))
    }
}

/*private extension String{
    /// 获取[1...3]的字符
    subscript( r : ClosedRange<Int>) -> String
    {
        let start = index(startIndex, offsetBy:max(r.lowerBound, 0))
        let end = index(startIndex, offsetBy: min(r.upperBound, count - 1))
        return String(self[start...end])
    }
}*/
